package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.po.CustRecords;
import com.example.domain.po.CustRecordsArchive;
import com.example.service.CustRecordsArchiveService;
import com.example.mapper.CustRecordsArchiveMapper;
import com.example.service.CustRecordsService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
* @author HUAWEI
* @description 针对表【cust_records_archive】的数据库操作Service实现
* @createDate 2025-02-09 16:22:55
*/
@Service
public class CustRecordsArchiveServiceImpl extends ServiceImpl<CustRecordsArchiveMapper, CustRecordsArchive>
    implements CustRecordsArchiveService{

    @Resource
    private CustRecordsService custRecordsService;


    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public Integer archiveOldRecords(int pageSize, LocalDateTime thresholdDate, Integer lastId) {
        LambdaQueryWrapper<CustRecords> wrapper = new LambdaQueryWrapper<>();
        wrapper.le(CustRecords::getSendTime, thresholdDate);
        if (lastId != null) {
            wrapper.gt(CustRecords::getId, lastId);
        }
        Page<CustRecords> page = new Page<>(1, pageSize);
        Page<CustRecords> pageInfo =custRecordsService.page(page, wrapper);
        List<CustRecords> records = pageInfo.getRecords();
        if (records.isEmpty()) {
            return null;
        }
        List<CustRecordsArchive> historyList = records.stream().map(item ->
                new CustRecordsArchive(null, item.getCustId(), item.getSendTime(), item.getSendFlag())
        ).toList();
        List<Integer> idsToDelete = records.stream().map(CustRecords::getId).toList();
        saveBatch(historyList);
        custRecordsService.removeBatchByIds(idsToDelete);
        return records.get(records.size() - 1).getId();
    }

}




